import 'dart:convert';
import 'dart:developer';
import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';

class MessagePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ListState();
  }
}

class ListState extends State {
  String msg = "这里是请求消息";

  void getInfo() async {
    setState(() {
      msg = "请稍等,数据请求中...";
    });
    _getIp();
  }

  _getIp() async {
    var url = "https://httpbin.org/ip";
    var httpClient = new HttpClient();

    var request = await httpClient.getUrl(Uri.parse(url));
    var response = await request.close();
    if (response.statusCode == HttpStatus.ok) {
      var json = await response.transform(utf8.decoder).join();
      var data = jsonDecode(json);
      log(data.toString());
      setState(() {
        msg = data["origin"];
      });
    } else {
      setState(() {
        msg = "网络请求出错";
      });
    }
  }

  void clearInfo() {
    setState(() {
      msg = "";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          child: Text(
            msg,
            style: TextStyle(color: Colors.red, fontSize: 21),
          ),
          margin: EdgeInsets.only(top: 8.0, bottom: 8.0),
        ),
        Container(
          height: 0.5,
          color: Colors.deepPurple,
        ),
        Row(
          children: [
            ButtonTheme(
                child: TextButton(
                    child: Row(children: [
                      Icon(Icons.clear),
                      Text(
                        "清空",
                        style: TextStyle(color: Colors.black),
                      )
                    ]),
                    onPressed: clearInfo)),
            IconButton(onPressed: getInfo, icon: Icon(Icons.adb))
          ],
        )
      ],
    );
  }
}
